﻿using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using Lamex.Base;
using Lamex.Common;
using Lamex.Interface;
using Lamex.Library;
using Lamex.Library.CommonClass;
using Lamex.Library.UI;
using Lamex.mIE.DalServer;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Lamex.mIE.UI
{
    public partial class Frm_IE_Part_TaskList : frmBaseChild
    {
        DataTable dtProc_Type_Ctrl = new DataTable();
        public Frm_IE_Part_TaskList()
        {
            InitializeComponent();
        }
        public Frm_IE_Part_TaskList(DataTable dt)
        {
            InitializeComponent();
            dtProc_Type_Ctrl = dt;
        }
        private void Frm_IE_Part_TaskList_Load(object sender, EventArgs e)
        {
            try { this.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理

            InitProductItem(dtProc_Type_Ctrl);
            InitializeForm();

        }

        protected void InitializeForm()
        {
            frmGridViewCust.RegisterGrid(gridView1);
            DevStyle.SetGridControlLayout(gridControl1, false);//表格设置-右键功能   
            // DevStyle.SetSummaryGridViewLayout(gridView1);//是否显示底部阴影条
            //DevStyle.SetDetailGridViewLayout(gridView1);  //是否显示筛选项                        
        }
        //产品类型初始化
        public void InitProductItem(DataTable dt)
        {
            if (dt.Rows.Count > 0)
            {
                this.txtProductItem.Properties.Items.Clear();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    this.txtProductItem.Properties.Items.Add(dt.Rows[i]["PROD_CATEGORY"].ToString());
                }
                txtProductItem.SelectIndex = 0;
                txtProductItem.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            }
            else
            {
                dt = BaseFactory<IE_Part_TaskList>.Instance.GetProductItem();
                this.txtProductItem.Properties.Items.Clear();
                if (dt.Rows.Count > 0)
                {
                    string[] list = dt.Rows[0]["FIELD_VALUE_OPTION"].ToString().Split(',');
                    foreach (var item in list)
                    {
                        this.txtProductItem.Properties.Items.Add(item);
                    }
                }
            }
        }
        //查询-只显示无上载标识数据
        public override void DoView(IButtonInfo sender)
        {
            //SplashScreenTool.ShowSplashScreen(typeof(WaitForm1));
            using (DevExpress.Utils.WaitDialogForm wdf = new DevExpress.Utils.WaitDialogForm("请稍等", "正在查询数据......", new Size(400, 80)))
            {
                string sqlWhere = "";
                string sql = @" SELECT [PROD_CATEGORY]
      ,[FILE_NO]
      ,[DWG_NO]
      ,T.[PART_NO]
      ,M.[CN_DESC]
      ,M.[EN_DESC]
      ,M.MODEL_NO
      ,[REF_MAT]
      ,[REF_DWG]
      ,[IMPORT_TIME]
      ,[IMPORT_USER]
      ,[CURRENT_USERS]
      ,[ROUTING_FLAG]
      ,[PARM_FLAG]
      ,[FEAT_FLAG]
      ,[REF_FLAG]
      ,[CAL_FLAG]
      ,[UPLOAD_FLAG]
      ,[LOCK_FLAG]
  FROM [LamexMESManager].[dbo].[IE_Part_TaskList] T
  LEFT jOIN [dbo].[IE_Part_MasterData] M ON T.PART_NO=M.PART_NO where 1=1  ";
                if (!string.IsNullOrEmpty(txtProductItem.Text))
                {
                    sqlWhere += " and PROD_CATEGORY like '%" + txtProductItem.Text + "%'";
                }
                if (!string.IsNullOrEmpty(txtDWG_No.Text))
                {
                    sqlWhere += " and DWG_NO like '%" + txtDWG_No.Text + "%'";
                }
                if (!string.IsNullOrEmpty(txtPart_No.Text))
                {
                    sqlWhere += " and T.PART_NO like '%" + txtPart_No.Text + "%'";
                }
                if (!ckUpload.Checked)
                {
                    sqlWhere += " and ISNULL(UPLOAD_FLAG,'')!='1' ";
                }

                sql = sql + sqlWhere + " and M.MRP_CONTROLLER not in ('WG1','PG1') and  ISNULL(LOCK_FLAG,'')!='1' order by IMPORT_TIME desc ";
                DataTable dt = BaseBuildSql.GetDataTableBySql(sql);
                gridControl1.DataSource = dt;
                gridView1.BestFitColumns();
                this.gridView1.OptionsView.ColumnAutoWidth = false;
            }
            //SplashScreenTool.CloseSplashScreen();
        }
        //导出-默认路径D:\MESTemp
        public override void DoExport(IButtonInfo sender)
        {
            if (!Directory.Exists(@"D:\MESTemp"))
                Directory.CreateDirectory(@"D:\MESTemp");
            SaveFileDialog fileDialog = new SaveFileDialog();
            fileDialog.Title = "导出Excel";
            fileDialog.InitialDirectory = @"D:\MESTemp";//导出默认路径
            fileDialog.Filter = "Excel文件(*.xlsx)|*.xlsx";//导出默认格式
            fileDialog.FileName = "MES_TEMP_" + DateTime.Now.ToString("yyMMdd_hhMMss");//导出默认名称
            DialogResult dialogResult = fileDialog.ShowDialog(this);
            if (dialogResult == DialogResult.OK)
            {
                //导出表【IE_Part_TaskList】中当前产品类型，无“工艺路线标识”的数据

                string sqlWhere = "";
                string sql = @" SELECT [PROD_CATEGORY]
      ,[FILE_NO]
      ,[DWG_NO]
      ,T.[PART_NO]
      ,M.[CN_DESC]
      --,M.[EN_DESC]
      ,[REF_MAT]
      ,[REF_DWG]
      ,[IMPORT_TIME]
      ,[IMPORT_USER]
      ,[CURRENT_USERS]
      ,[ROUTING_FLAG]
      ,[PARM_FLAG]
      ,[FEAT_FLAG]
      ,[REF_FLAG]
      ,[CAL_FLAG]
      ,[UPLOAD_FLAG]
      ,[LOCK_FLAG]
  FROM [LamexMESManager].[dbo].[IE_Part_TaskList] T
  LEFT jOIN [dbo].[IE_Part_MasterData] M ON T.PART_NO=M.PART_NO where 1=1 and M.MRP_CONTROLLER not in ('WG1','PG1') ";
                if (!string.IsNullOrEmpty(txtProductItem.Text))
                {
                    sqlWhere += " and PROD_CATEGORY like '%" + txtProductItem.Text + "%'";
                }
                if (!string.IsNullOrEmpty(txtDWG_No.Text))
                {
                    sqlWhere += " and DWG_NO like '%" + txtDWG_No.Text + "%'";
                }
                if (!string.IsNullOrEmpty(txtPart_No.Text))
                {
                    sqlWhere += " and T.PART_NO like '%" + txtPart_No.Text + "%'";
                }
                if (!ckUpload.Checked)
                {
                    sqlWhere += "and ISNULL(UPLOAD_FLAG,'')!='1' ";
                }
                sql = sql + sqlWhere + " order by IMPORT_TIME desc ";
                DataTable dtList = BaseBuildSql.GetDataTableBySql(sql);

                GridControl grid = new GridControl();
                GridView view = new GridView();
                grid.ViewCollection.Add(view);
                grid.MainView = view;
                view.GridControl = grid;
                foreach (DataColumn dc in dtList.Columns)
                {
                    DevExpress.XtraGrid.Columns.GridColumn gridColumnNumber = view.Columns.AddVisible(dc.ColumnName);
                    gridColumnNumber.FieldName = dc.ColumnName;
                }
                grid.DataSource = dtList;
                this.Controls.Add(grid);
                grid.ForceInitialize();//强制初始化
                //Font font = new Font("宋体", 11, FontStyle.Bold); 
                //view.Appearance.HeaderPanel.Font = font;
                //view.Appearance.Row.Font = font;            
                view.BestFitColumns();
                view.OptionsView.ColumnAutoWidth = false;
                view.OptionsView.ShowAutoFilterRow = false;
                view.OptionsPrint.PrintHorzLines = false;//去掉水平网格线
                view.OptionsPrint.PrintVertLines = false;//去掉垂直网格线
                view.ExportToXlsx(fileDialog.FileName);
                if (DevExpress.XtraEditors.XtraMessageBox.Show("导出成功，是否打开文件？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    System.Diagnostics.Process.Start(fileDialog.FileName);//打开指定路径下的文件

            }
        }
        //导入
        public override void DoImport(IButtonInfo sender)
        {
            #region 按钮权限
            if (!BuildSqlHelper.IsExistList("IE_Part_TaskList", "LamexMESManager")) return;
            #endregion
            //DevExpress.XtraEditors.XtraMessageBox.Show("未上载数据中，图纸编号+部件编号重复时，原有记录将进行覆盖！\r\n导入标题必须为【文件编号】+【图纸编号】+【部件编号】+【参考号码】！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            // string[] list = { "Laminate", "Panel", "Seating", "MCG" };
            DevExpress.XtraEditors.XtraMessageBox.Show("导入标题必须为【文件编号】+【图纸编号】+【部件编号】+【参考号码】！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            OpenFileDialog dlg = new OpenFileDialog();
            DataTable dtEqual = new DataTable();//获取导入文件和数据库未上载标识 图纸号+部件号相同值
            List<string> Temp1 = new List<string>();
            List<string> Temp2 = new List<string>();
            List<string> PartNoList_1 = new List<string>();
            List<string> PartNoList_2 = new List<string>();
            List<string> PartNoList_3 = new List<string>();
            List<string> DwgNoList = new List<string>();
            StringBuilder sbFilter1 = new StringBuilder();
            StringBuilder sbFilter2 = new StringBuilder();
            DataTable dtError = Common.GetTable.GetTaskList_Error();//存错误订单
            DataTable dtResult = Common.GetTable.GetTaskList();
            // DataTable dtCateTory = Common.GetTable.GetTaskList_Temp();
            int suceesCount = 0, failCount = 0, sumCount = 0;
            if (DialogResult.OK == dlg.ShowDialog())
            {
                try
                {
                    SplashScreenTool.ShowSplashScreen(typeof(WaitForm1));
                    string path = dlg.FileName;
                    //导入EXCEL转换成Table
                    // DataTable dtImport = Lamex.Common.ExecelHelper.ExcelToDataTable(path, 1);
                    DataTable dtImport = Lamex.Common.ExecelHelper.ExcelConvertDataTable(0, true, path);
                    dtImport = RemoveEmpty(dtImport);
                    if (dtImport.Rows.Count <= 0)
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show("导入数据为空！");
                        return;
                    }
                    for (int i = 0; i < dtImport.Rows.Count; i++)
                    {
                        if (string.IsNullOrWhiteSpace(dtImport.Rows[i]["图纸编号"].ToString().Trim()))
                        {
                            DevExpress.XtraEditors.XtraMessageBox.Show("图纸编号不允许为空！");
                            return;
                        }
                        if (string.IsNullOrWhiteSpace(dtImport.Rows[i]["部件编号"].ToString().Trim()))
                        {
                            DevExpress.XtraEditors.XtraMessageBox.Show("部件编号不允许为空！");
                            return;
                        }
                        if (string.IsNullOrWhiteSpace(dtImport.Rows[i]["参考号码"].ToString().Trim()))
                        {
                            DevExpress.XtraEditors.XtraMessageBox.Show("参考号码不允许为空！");
                            return;
                        }
                        PartNoList_1.Add(dtImport.Rows[i]["部件编号"].ToString());
                        DwgNoList.Add(dtImport.Rows[i]["图纸编号"].ToString());
                    }
                    sumCount = dtImport.Rows.Count;//导入总数

                    //获取主数据表存在的partNo
                    DataTable dtTemp = GetMRP(PartNoList_1);
                    // int PartNoCount_2 = dtTemp.Rows.Count;

                    PartNoList_2 = dtTemp.AsEnumerable().Select(d => d.Field<string>("PART_NO")).ToList();

                    PartNoList_3 = PartNoList_1.Except(PartNoList_2).ToList();//取得导入数据不存在主数据表的数据
                    for (int i = 0; i < PartNoList_3.Count; i++)
                    {
                        //插入错误表
                        DataRow dataRow = dtError.NewRow();
                        dataRow["文件编号"] = dtImport.Select("部件编号='" + PartNoList_3[i].ToString() + "'").CopyToDataTable().Rows[0]["文件编号"];
                        dataRow["图纸编号"] = dtImport.Select("部件编号='" + PartNoList_3[i].ToString() + "'").CopyToDataTable().Rows[0]["图纸编号"];
                        dataRow["部件编号"] = PartNoList_3[i].ToString();
                        dataRow["参考号码"] = dtImport.Select("部件编号='" + PartNoList_3[i].ToString() + "'").CopyToDataTable().Rows[0]["参考号码"];
                        dataRow["提示"] = "无主数据";
                        dtError.Rows.Add(dataRow);
                    }
                    //  }
                    //获取是否存在任务清单
                    DataTable dtRepeat = GetIsRepeatPartNo(PartNoList_1, DwgNoList);
                    if (dtRepeat.Rows.Count > 0)
                    {
                        for (int i = 0; i < dtRepeat.Rows.Count; i++)
                        {
                            //插入错误表
                            DataRow dataRow = dtError.NewRow();
                            dataRow["文件编号"] = dtImport.Select("部件编号='" + dtRepeat.Rows[i]["PART_NO"].ToString() + "'").CopyToDataTable().Rows[0]["文件编号"];
                            dataRow["图纸编号"] = dtImport.Select("部件编号='" + dtRepeat.Rows[i]["PART_NO"].ToString() + "'").CopyToDataTable().Rows[0]["图纸编号"];
                            dataRow["部件编号"] = dtRepeat.Rows[i]["PART_NO"].ToString();
                            dataRow["参考号码"] = dtImport.Select("部件编号='" + dtRepeat.Rows[i]["PART_NO"].ToString() + "'").CopyToDataTable().Rows[0]["参考号码"];
                            dataRow["提示"] = "重复导入";
                            dtError.Rows.Add(dataRow);
                        }
                    }

                    if (dtError.Rows.Count > 0)
                    {
                        //导出错误清单
                        // GetErrorList(dtError);

                        //去掉导入表中存在的错误列表                      
                        for (int j = 0; j < dtError.Rows.Count; j++)
                        {
                            DataRow[] dr = dtImport.Select("部件编号='" + dtError.Rows[j]["部件编号"].ToString() + "'");

                            foreach (DataRow row in dr)
                            {
                                dtImport.Rows.Remove(row);
                            }
                        }
                        //获取产品类型
                        List<string> PartNoList_MRP = dtImport.AsEnumerable().Select(d => d.Field<string>("部件编号")).ToList();
                        DataTable dt_MRP = GetMRP(PartNoList_MRP);

                        dtResult = GET_PROD_CATEGORY(dt_MRP, dtImport, dtResult);
                        suceesCount = dtResult.Rows.Count;
                        failCount = sumCount - suceesCount;
                    }
                    else
                    {
                        List<string> PartNoList_MRP = dtImport.AsEnumerable().Select(d => d.Field<string>("部件编号")).ToList();
                        DataTable dt_MRP = GetMRP(PartNoList_MRP);
                        dtResult = GET_PROD_CATEGORY(dt_MRP, dtImport, dtResult);
                        suceesCount = dtResult.Rows.Count;
                        // failCount = sumCount - suceesCount;
                    }


                    //添加导入时间和导入用户
                    //添加两新列，其值为默认值
                    DataColumn dc1 = new DataColumn("IMPORT_TIME", typeof(DateTime));
                    dc1.DefaultValue = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                    dtResult.Columns.Add(dc1);
                    DataColumn dc2 = new DataColumn("IMPORT_USER", typeof(string));
                    dc2.DefaultValue = Lamex.Common.Loginer.CurrentUser.AccountName;
                    dtResult.Columns.Add(dc2);

                    //批量插入数据库
                    if (BaseBuildSql.ExcuteInsert(dtResult, "IE_Part_TaskList"))
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show("共【" + sumCount + "】条,成功【" + suceesCount + "】条,失败【" + failCount + "】条", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        if (dtError.Rows.Count > 0)
                        {
                            //导出错误清单
                            GetErrorList(dtError);
                        }
                        //按导入时间降序刷新
                        DoView(null);
                    }

                    SplashScreenTool.CloseSplashScreen();

                }
                catch (Exception ex)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
                    SplashScreenTool.CloseSplashScreen();
                }
            }

        }

        //删除支持单选、多选、跳选，提前用户
        public override void DoDelete(IButtonInfo sender)
        {
            #region 按钮权限
            if (!BuildSqlHelper.IsExistList("IE_Part_TaskList", "LamexMESManager")) return;
            #endregion
            //List<string> listDWNO = new List<string>();
            //List<string> listPARTNO = new List<string>();
            //StringBuilder sbFilter1 = new StringBuilder();
            //StringBuilder sbFilter2 = new StringBuilder();
            //int[] rownumber = this.gridView1.GetSelectedRows();//获取选中行号；
            //if (rownumber.Length > 0)
            //{
            //    foreach (var item in rownumber)
            //    {
            //        DataRow row = this.gridView1.GetDataRow(item);//根据行号获取相应行的数据；
            //        listDWNO.Add(row[2].ToString());//图纸编号
            //        listPARTNO.Add(row[3].ToString());//部件编号
            //    }
            //    sbFilter1.AppendFormat(@" AND DWG_NO IN ('{0}')", string.Join("','", listDWNO.ToArray()));
            //    sbFilter2.AppendFormat(@" AND PART_NO IN ('{0}')", string.Join("','", listPARTNO.ToArray()));

            //    string sqlDel = @"Delete  FROM IE_Part_TaskList where 1=1  " + sbFilter1 + " " + sbFilter2 + " AND ISNULL(UPLOAD_FLAG,'')!='1' ";

            //    if (ConfirmDelete() == DialogResult.Cancel)
            //        return;
            //    else
            //    {
            //        int n = BaseBuildSql.ExecuteNonQuery(sqlDel);
            //        DevExpress.XtraEditors.XtraMessageBox.Show("删除成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //        DoView(null);
            //    }
            //}
            //else
            //{
            //    DevExpress.XtraEditors.XtraMessageBox.Show("无数据选中，请勾选需要删除的记录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    return;
            //}

        }
        public DialogResult ConfirmDelete()
        {
            return DevExpress.XtraEditors.XtraMessageBox.Show("确定要删除吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
        }
        //双击页面跳转事件
        private void gridView1_DoubleClick(object sender, EventArgs e)
        {

            //所有双击事件按图纸来保存
            /*1.取消工艺路线及部件特征维护界面的[按图纸创建]及[按部件调整]控件
              2.提供按图纸编号及部件编号查询功能，支持批量修改，且修改的数据如已上载，提示不可修改
              3.任务清单增加跳转功能，且在状态栏显示跳转要求，具体要求如下：
              a.无上载标识且未被锁定
              b.双击工艺标识列，跳转对应图纸的工艺路线维护界面，如已有特征标识、计算标识需取消
              c.双击参数标识列，跳转对应图纸的数据参数维护界面，如已有计算标识需取消
              d.双击特征标识列，跳转对应图纸的部件特征维护界面，如已有计算标识需取消*/
            int iRow = gridView1.FocusedRowHandle;
            string UPLOAD_FLAG = gridView1.GetRowCellDisplayText(iRow, "UPLOAD_FLAG").ToString();//上载标识
            string CURRENT_USERS = gridView1.GetRowCellDisplayText(iRow, "CURRENT_USERS").ToString();//锁定人
            string DWG_NO = gridView1.GetRowCellDisplayText(iRow, "DWG_NO").ToString();//图纸号
            string PART_NO = gridView1.GetRowCellDisplayText(iRow, "PART_NO").ToString();//部件号
            string PROD_CATEGORY = gridView1.GetRowCellDisplayText(iRow, "PROD_CATEGORY").ToString();//产品类型
            string strROUTING_FLAG = gridView1.GetRowCellDisplayText(iRow, "ROUTING_FLAG").ToString();//工艺标识
            string strPARM_FLAG = gridView1.GetRowCellDisplayText(iRow, "PARM_FLAG").ToString();//尺寸标识
            string strFEAT_FLAG = gridView1.GetRowCellDisplayText(iRow, "FEAT_FLAG").ToString();//特征标识
                                                                                                // string strLOCK_FLAG = gridView1.GetRowCellDisplayText(iRow, "LOCK_FLAG").ToString();//禁用标识

            if (CURRENT_USERS.Trim().Length > 0)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("当前记录正在被【" + CURRENT_USERS + "】编辑中！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (!string.IsNullOrEmpty(UPLOAD_FLAG.Trim()))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("当前记录已上载，不允许编辑！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            //if (!string.IsNullOrEmpty(strLOCK_FLAG.Trim()))
            //{
            //    DevExpress.XtraEditors.XtraMessageBox.Show("当前记录已禁用，不允许编辑！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    return;
            //}
            using (DevExpress.Utils.WaitDialogForm wdf = new DevExpress.Utils.WaitDialogForm("请稍等", "正在加载窗体......", new Size(400, 80)))
            {
                //跳转到进度查询画面
                if (gridView1.FocusedColumn.FieldName == "PROD_CATEGORY" ||
                gridView1.FocusedColumn.FieldName == "FILE_NO")
                {
                }
                //跳转到工艺路线画面
                if (gridView1.FocusedColumn.FieldName == "ROUTING_FLAG")
                {
                    //取消特征标识、计算标识 按图纸取消
                    string Canel_Sql = "";
                    if (DWG_NO == "NIL" || string.IsNullOrEmpty(DWG_NO))
                        Canel_Sql = @"update IE_Part_TaskList set CAL_FLAG='',FEAT_FLAG='' where PART_NO='" + PART_NO + "'";
                    else
                        Canel_Sql = @"update IE_Part_TaskList set CAL_FLAG='',FEAT_FLAG='' where DWG_NO='" + DWG_NO + "'";
                    int m = BaseBuildSql.ExecuteNonQuery(Canel_Sql);
                    // SplashScreenTool.ShowSplashScreen(typeof(WaitForm1));
                    //打开窗体    
                    this.Invoke(new Action(() =>
                    {
                        Frm_IE_Routing_Part form = new Frm_IE_Routing_Part(DWG_NO, PROD_CATEGORY, PART_NO);
                        DataTable dt = BaseBuildSql.GetDataTableBySql("select *　from　sys_menu where winformid='menuIE_Routing'");
                        MdiTools.OpenChildForm_Param(this.MdiParent as IMdiForm, form, dt.Rows[0]["id"].ToString());
                        form.DoView(null);
                    }));
                    //SplashScreenTool.CloseSplashScreen();
                }
                //跳转到参数录入画面
                if (gridView1.FocusedColumn.FieldName == "PARM_FLAG")
                {
                    if (PROD_CATEGORY == "Seating")
                    {
                        if (strROUTING_FLAG == "1")
                        {
                            string strRouting = @"SELECT c.ROUTING_CODE
  FROM [LamexMESManager].[dbo].[IE_Part_Routing] r 
  join [LamexMESManager].[dbo].[IE_Routing_Combination] c on r.GROUP_CODE=c.GROUP_CODE
  where  r.PART_NO='" + PART_NO + "'";
                            DataTable dtrouting = BaseBuildSql.GetDataTableBySql(strRouting);
                            if (dtrouting.Rows.Count > 0)
                            {
                                string[] listR = dtrouting.Rows[0]["ROUTING_CODE"].ToString().Split('_');
                                if (listR.Contains("S02") && !listR.Contains("S03"))
                                {
                                    //打开布
                                    Frm_IE_Part_SizeParmList_Fabric form = new Frm_IE_Part_SizeParmList_Fabric(PART_NO);
                                    DataTable dt = BaseBuildSql.GetDataTableBySql("select *　from　sys_menu where winformid='menuIE_SizePar_SeatingFabric'");
                                    MdiTools.OpenChildForm_Param(this.MdiParent as IMdiForm, form, dt.Rows[0]["id"].ToString());
                                    form.DoView(null);
                                }
                                else if (listR.Contains("S03") && !listR.Contains("S02"))
                                {
                                    //打开棉
                                    Frm_IE_Part_SizeParmList_Foam form = new Frm_IE_Part_SizeParmList_Foam(PART_NO);
                                    DataTable dt = BaseBuildSql.GetDataTableBySql("select *　from　sys_menu where winformid='menuIE_SizePar_SeatingFoam'");
                                    MdiTools.OpenChildForm_Param(this.MdiParent as IMdiForm, form, dt.Rows[0]["id"].ToString());
                                    form.DoView(null);
                                }
                                else if (listR.Contains("S03") && listR.Contains("S02"))
                                {
                                    //打开棉和布
                                    Frm_IE_Part_SizeParmList_Fabric form = new Frm_IE_Part_SizeParmList_Fabric(PART_NO);
                                    DataTable dt = BaseBuildSql.GetDataTableBySql("select *　from　sys_menu where winformid='menuIE_SizePar_SeatingFabric'");
                                    MdiTools.OpenChildForm_Param(this.MdiParent as IMdiForm, form, dt.Rows[0]["id"].ToString());
                                    form.DoView(null);
                                    Frm_IE_Part_SizeParmList_Foam form1 = new Frm_IE_Part_SizeParmList_Foam(PART_NO);
                                    DataTable dt1 = BaseBuildSql.GetDataTableBySql("select *　from　sys_menu where winformid='menuIE_SizePar_SeatingFoam'");
                                    MdiTools.OpenChildForm_Param(this.MdiParent as IMdiForm, form1, dt1.Rows[0]["id"].ToString());
                                    form1.DoView(null);
                                }
                                else
                                {
                                    //弹出提示
                                    DevExpress.XtraEditors.XtraMessageBox.Show("次产品不经过S02、S03,不需要布棉尺寸！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    return;
                                }
                            }
                        }
                        else
                        {
                            //弹出提示
                            DevExpress.XtraEditors.XtraMessageBox.Show("请先录入工艺路线！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }
                    }
                    else
                    {
                        //取消特征标识、计算标识 按图纸取消
                        string Canel_Sql = "";
                        if (DWG_NO == "NIL" || string.IsNullOrEmpty(DWG_NO))
                            Canel_Sql = @"update IE_Part_TaskList set CAL_FLAG='' where PART_NO='" + PART_NO + "'";
                        else
                            Canel_Sql = @"update IE_Part_TaskList set CAL_FLAG='' where DWG_NO='" + DWG_NO + "'";
                        int m = BaseBuildSql.ExecuteNonQuery(Canel_Sql);
                        //打开窗体
                        this.Invoke(new Action(() =>
                        {
                            Frm_IE_Part_SizeParmList_Excel form = new Frm_IE_Part_SizeParmList_Excel(DWG_NO, PROD_CATEGORY);
                            DataTable dt = BaseBuildSql.GetDataTableBySql("select *　from　sys_menu where winformid='menuIE_SizePar_Laminate'");

                            MdiTools.OpenChildForm_Param(this.MdiParent as IMdiForm, form, dt.Rows[0]["id"].ToString());
                            form.DoView(null);
                        }));
                    }
                }
                //跳转到部件录入画面
                if (gridView1.FocusedColumn.FieldName == "FEAT_FLAG")
                {
                    //取消特征标识、计算标识 按图纸取消
                    string Canel_Sql = "";
                    if (DWG_NO == "NIL" || string.IsNullOrEmpty(DWG_NO))
                        Canel_Sql = @"update IE_Part_TaskList set CAL_FLAG='' where PART_NO='" + PART_NO + "'";
                    else
                        Canel_Sql = @"update IE_Part_TaskList set CAL_FLAG='' where DWG_NO='" + DWG_NO + "'";
                    int m = BaseBuildSql.ExecuteNonQuery(Canel_Sql);
                    // SplashScreenTool.ShowSplashScreen(typeof(WaitForm1));
                    //打开窗体    
                    this.Invoke(new Action(() =>
                    {
                        Frm_IE_PartFeature form = new Frm_IE_PartFeature(DWG_NO, PROD_CATEGORY, PART_NO, strFEAT_FLAG);
                        DataTable dt = BaseBuildSql.GetDataTableBySql("select *　from　sys_menu where winformid='menuIE_PartFeature'");
                        MdiTools.OpenChildForm_Param(this.MdiParent as IMdiForm, form, dt.Rows[0]["id"].ToString());
                        form.DoView(null);
                    }));
                    // SplashScreenTool.CloseSplashScreen();
                }
            }

        }

        private void txtProductItem_UcTextChanged(object sender, EventArgs e)
        {
            DoView(null);
        }
        //导入时获取主数据存在部件号
        public DataTable GetMRP(List<string> PartNoList)
        {
            DataTable dt = new DataTable();
            StringBuilder sbFilter = new StringBuilder();
            sbFilter.AppendFormat(@" AND PART_NO IN ('{0}')", string.Join("','", PartNoList.ToArray()));
            string sql = @"SELECT PART_NO,MRP_CONTROLLER  FROM IE_Part_MasterData where 1=1  " + sbFilter + " ";
            dt = BaseBuildSql.GetDataTableBySql(sql);
            return dt;
        }
        //根据MRP获取产品类型
        public DataTable GET_PROD_CATEGORY(DataTable dtMRP, DataTable dtImport, DataTable dtResult)
        {
            DataTable dtNew = dtResult.Copy();
            DataTable dtCatetory = new DataTable();
            List<string> list = new List<string>();
            StringBuilder sbFilter = new StringBuilder();

            //string sql = @"SELECT PART_NO,MRP_CONTROLLER  FROM IE_Part_MasterData where 1=1  " + sbFilter + " ";
            //dt = BaseBuildSql.GetDataTableBySql(sql);
            for (int i = 0; i < dtMRP.Rows.Count; i++)
            {
                string strMRP = dtMRP.Rows[i]["MRP_CONTROLLER"].ToString();
                list.Add(strMRP);
            }
            sbFilter.AppendFormat(@" AND MRP_CONTROLLER IN ('{0}')", string.Join("','", list.ToArray()));
            string sql = @"select PROD_CATEGORY,MRP_CONTROLLER from IE_Part_Category where 1=1  " + sbFilter + " ";
            dtCatetory = BaseBuildSql.GetDataTableBySql(sql);

            //合并成一个新的dt
            var query1 =
                from mrp in dtMRP.AsEnumerable()
                from catetory in dtCatetory.AsEnumerable()
                from import in dtImport.AsEnumerable()
                where mrp.Field<String>("MRP_CONTROLLER") == catetory.Field<String>("MRP_CONTROLLER") &&
                import.Field<String>("部件编号") == mrp.Field<String>("PART_NO")
                select new
                {
                    FILE_NO = import.Field<String>("文件编号"),
                    DWG_NO = import.Field<String>("图纸编号"),
                    PART_NO = mrp.Field<String>("PART_NO"),
                    //MRP_CONTROLLER = mrp.Field<String>("MRP_CONTROLLER"),
                    REF_DWG = import.Field<String>("参考号码"),
                    PROD_CATEGORY = catetory.Field<String>("PROD_CATEGORY"),
                };
            foreach (var obj in query1)
            {
                dtNew.Rows.Add(obj.PROD_CATEGORY, obj.FILE_NO, obj.DWG_NO, obj.PART_NO, obj.REF_DWG);
            }
            DataView dv = dtNew.DefaultView;
            dtNew = dv.ToTable(true, new string[] { "PROD_CATEGORY", "FILE_NO", "DWG_NO", "PART_NO", "REF_MAT" });
            return dtNew;

        }
        //导入时获取是否存在重复数据
        public DataTable GetIsRepeatPartNo(List<string> PartNoList, List<string> DwgNoList)
        {
            DataTable dt = new DataTable();
            StringBuilder sbFilter = new StringBuilder();
            StringBuilder sbFilter1 = new StringBuilder();
            sbFilter.AppendFormat(@" AND PART_NO IN ('{0}')", string.Join("','", PartNoList.ToArray()));
            sbFilter1.AppendFormat(@" AND DWG_NO IN ('{0}')", string.Join("','", DwgNoList.ToArray()));
            string sql = @"SELECT PART_NO,DWG_NO  FROM IE_Part_TaskList where 1=1  " + sbFilter + " " + sbFilter1 + "";
            dt = BaseBuildSql.GetDataTableBySql(sql);
            return dt;
        }
        //导出错误清单
        public void GetErrorList(DataTable dtTemp)
        {
            if (!Directory.Exists(@"D:\MESTemp"))
                Directory.CreateDirectory(@"D:\MESTemp");
            SaveFileDialog fileDialog = new SaveFileDialog();
            fileDialog.Title = "导出错误列表";
            fileDialog.InitialDirectory = @"D:\MESTemp\";//导出默认路径
            fileDialog.Filter = "Excel文件(*.xlsx)|*.xlsx";//导出默认格式
            fileDialog.FileName = "MES_TEMP_" + DateTime.Now.ToString("yyMMdd_hhMMss");//导出默认名称

            GridControl grid = new GridControl();
            GridView view = new GridView();
            grid.ViewCollection.Add(view);
            grid.MainView = view;
            view.GridControl = grid;
            foreach (DataColumn dc in dtTemp.Columns)
            {
                DevExpress.XtraGrid.Columns.GridColumn gridColumnNumber = view.Columns.AddVisible(dc.ColumnName);
                gridColumnNumber.FieldName = dc.ColumnName;
            }
            grid.DataSource = dtTemp;
            this.Controls.Add(grid);
            grid.ForceInitialize();//强制初始化         
            view.BestFitColumns();
            view.OptionsView.ColumnAutoWidth = false;
            view.OptionsView.ShowAutoFilterRow = false;
            view.OptionsPrint.PrintHorzLines = false;//去掉水平网格线
            view.OptionsPrint.PrintVertLines = false;//去掉垂直网格线
            view.ExportToXlsx(fileDialog.InitialDirectory + fileDialog.FileName + ".xlsx");
            //if (DevExpress.XtraEditors.XtraMessageBox.Show("生成错误信息列表成功，是否打开文件？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
            System.Diagnostics.Process.Start(fileDialog.InitialDirectory + fileDialog.FileName + ".xlsx");//打开指定路径下的文件

        }
        //去除Excel转DataTable的空白行
        private DataTable RemoveEmpty(DataTable dt)
        {
            List<DataRow> removelist = new List<DataRow>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                bool IsNull = true;
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    if (!string.IsNullOrEmpty(dt.Rows[i][j].ToString().Trim()))
                    {
                        IsNull = false;
                    }
                }
                if (IsNull)
                {
                    removelist.Add(dt.Rows[i]);
                }
            }
            for (int i = 0; i < removelist.Count; i++)
            {
                dt.Rows.Remove(removelist[i]);
            }
            return dt;
        }
    }
}
